package com.gss.plugin.oauth2.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gss.entity.R;
import com.gss.entity.enums.ConstantEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author DYang
 * @date 2023/7/21
 * token异常处理
 */
@Slf4j
public class ResourcePointHandler extends OAuth2AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {

        Throwable cause = authException.getCause();
        //自定义返回格式内容
        R<Object> res = R.error(ConstantEnum.NON_AUTH);
        res.setDesc(authException.getMessage());

        if (cause instanceof OAuth2AccessDeniedException) {
            res.setMsg("资源ID不在resource_ids范围内");
        }  else if (cause instanceof InvalidTokenException) {
            res.setMsg("Token解析失败");
        }else if (authException instanceof InsufficientAuthenticationException) {
            res.setMsg("未携带token");
        }else{
            res.setMsg("未知异常信息");
        }

        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=UTF-8");

        PrintWriter printWriter = response.getWriter();
        printWriter.write(new ObjectMapper().writeValueAsString(res));
        printWriter.flush();
        printWriter.close();
    }

}
